<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 服务类目
 *
 * @icon fa fa-circle-o
 */
class Cate extends Backend
{

    /**
     * Cate模型对象
     * @var \app\admin\model\deerhome\Cate
     */
    protected $model = null;
    protected $multiFields="status,home,can_apply";
     /**
     * 是否是关联查询
     */
    protected $relationSearch = true;
    protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Cate;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function cate1()
    {
        $list=db('deerhome_cate')->field('id,name')->where('cate_id',0)->where('status',1)->select();
        return json(["total" => count($list), "list" => $list]);
    }
    public function cate2()
    {
        $cate_type=$this->request->param('cate_type',1,'intval');
        $id=$this->request->param('id',0,'intval');
        if($id>0){
            $list=$this->model->field('id as value,name')->where('cate_id',$id)->where('status',1)->select();
            return json(["code" => 1, "data" => $list]);
        }
        $where=[];
        $where['cate_id']=0;
        $where['status']=1;
        if($cate_type==1 || $cate_type==2){
            $where['cate_type']=$cate_type;
        }
        $list=$this->model->field('id as value,name')->where($where)->select();
        return json(["code" => 1, "data" => $list]);
    }
    public function selectpage2()
    {
        $keyField= $this->request->request('keyField','','trim');
        $keyValue= $this->request->request('keyValue','','trim');
        $name= $this->request->request('name','','trim');
        $cate_type=$this->request->param('cate_type',1,'intval');
        $where=[];
        $where["c.cate_type"]=$cate_type;
        if($keyField=='id' && $keyValue!=''){
            $where["c.id"]=$keyValue;
        }

        $list=db('deerhome_cate')->alias('c')
        ->join("deerhome_cate c2","c.cate_id=c2.id","left")
        ->field('c.id,concat(c.name," / ",c2.name) as name')
        ->where('c.cate_id','>',0)
        ->where($where)
        ->where("concat(c.name,'/',c2.name) like '%{$name}%'")
        ->where('c.status',1)
        ->order("c2.id asc,c.id asc")
        ->select();
        return json(["total" => count($list), "rows" => $list]);
    }
    public function selectpage()
    {
        $this->relationSearch = false;
        $this->searchFields = ['name'];
        $this->filterFields = ['cate_id'];
        return parent::selectpage();
    }
    public function index()
    {
        if (!$this->request->isAjax())
        {
            return $this->view->fetch();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        // dump($where);
        $ruleList = $this->model->where($where)->order('weigh ASC,id ASC')->select();
        $list=[];
        $fa=[];
        $son=[];
        foreach ($ruleList as $k => $v) {
            if($v['cate_id']==0){
                $fa[$k]=$v;
                continue;
            }
            $son[$k]=$v;
        }
        foreach ($fa as $k => $v) {
            $v['fw']='-';
            \array_push($list,$v);
            foreach ($son as $k2 => $v2) {
                if($v2['cate_id']==$v['id']){
                    $v2['name']='├ '.$v2['name'];
                    $v2['fw']=Db::name("deerhome_items")->where('cate_id',$v2['id'])->count();
                    \array_push($list,$v2);
                }
            }
        }
        $result = array("total" => count($ruleList), "rows" => $list);
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['name']=trim($params['name']);
        if($params['cate_id']>0){
            $cate=$this->model->where('id',$params['cate_id'])->find();
            if(!$cate){
                $this->error('上级分类不存在');
            }
            $params['cate_type']=$cate['cate_type'];
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
   
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['id']==$params['cate_id']){
            $this->error('自己不能是自己的上级分类');
        }
        $params['name']=trim($params['name']);
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $err="";
        //检查是否满足删除条件
        foreach ($list as $k => $v) {
            if($v['cate_id']==0){
                $son=$this->model->where('cate_id',$v['id'])->count();
                if($son>0){
                    $err.="选择的分类有子分类，请先删除子分类再删除父级分类";
                    break;
                }
            }
            $count=Db::name("deerhome_items")->where('cate_id',$v['id'])->count();
            if($count>0){
                $err.="请先删除或移除该分类下的服务项目";
            }
        }
        if($err!=""){
            $this->error($err);
        }
        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
